package net.wicp.tams.common.connector.executor.busi;

import org.apache.commons.lang3.ArrayUtils;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Plugin;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.connector.executor.IBusiManager;

@Slf4j
public class ClassLoadManager implements IBusiManager {

	private final Plugin plugin;

	private final String[] packageBases;

	public ClassLoadManager(String dirpath, String... packageBases) {
		this.plugin = new Plugin(dirpath, "net.wicp.tams.common.connector.executor.IBusiApp",
				Thread.currentThread().getContextClassLoader());
		this.packageBases = packageBases;
		Thread.currentThread().setContextClassLoader(plugin.getLoad().getClassLoader());// 需要加载前设置好classload
	}

	@Override
	public IBusiApp getBean(String appKey) {
		if (ArrayUtils.isNotEmpty(packageBases)) {
			for (String packageBase : packageBases) {
				String formatestr = packageBase.endsWith(".") ? "%s%s" : "%s.%s";
				String className = String.format(formatestr, packageBase, appKey);
				try {
					Class<?> classz = plugin.loadSingleByClassName(className);
					IBusiApp retobj = (IBusiApp) classz.newInstance();
					return retobj;
				} catch (Exception e) {
					log.error("{}未找到{}", packageBase, appKey);
				}
			}
		}
		return null;
	}

	@Override
	public void refresh() {
		plugin.refresh();
	}
}
